<template>
    <div class="app-container">
      <!-- 输入表单 -->
      <el-form label-width="120px">
        <el-form-item label="商品名">
          <el-input v-model="goods.name" />
        </el-form-item>
        
        <el-form-item label="商品价格">
            <el-input v-model="goods.price" />
        </el-form-item>
        <el-form-item label="商品库存">
          <el-input-number v-model="goods.stock" :min="0"/>
        </el-form-item>
  
        <el-form-item>
          <el-button type="primary" @click="saveOrUpdate()">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </template>
  
  
  <script>
import goods from "@/api/goods/goods";
  export default {
      data() {
          return {
                BASE_API: 'http://localhost:8888',
              goods:{
                stock: 0,
                price: 0
              }
          }
      },
      created() {
        if(this.$route.params.id){
          const id = this.$route.params.id;
          this.fetchDataById(id)
        }
      },
      methods: {
        fetchDataById(id){
          goods.getGoodsById(id)
          .then(response => {
            this.goods = response.data
          })
        },
        //添加
        save(){
          goods.saveGoods(this.goods)
          .then((response) => {
              this.$message({
                  type: 'success',
                  message: '添加成功!'
              });
              //跳转列表页面
              this.$router.push({path:'/goods/list'})
          })
        },
        //修改
        update(){
          goods.updateGoods(this.goods)
          .then((response) => {
              this.$message({
                  type: 'success',
                  message: '修改成功!'
              });
              //跳转列表页面
              this.$router.push({path:'/goods/list'})
          })
        },
        saveOrUpdate(){
          if(this.goods.id){
            this.update()
          }else{
            this.save()
          }
        },
      },
      
  }
  </script>

  <style>
  </style>